<template>
  <div class="dashboard-container">
    <div class="dashboard-text">
      <h1>欢迎使用 ZenithMind 后台管理系统</h1>
      <p>这是一个基于 Vue 3 + Element Plus 的现代化后台管理系统</p>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row" v-loading="loading">
      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card primary">
          <div class="stat-icon">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.userCount?.toLocaleString() || 0 }}</div>
            <div class="stat-label">用户总数</div>
            <div class="stat-extra">今日新增: {{ stats.todayNewUsers || 0 }}</div>
          </div>
        </div>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card success">
          <div class="stat-icon">
            <el-icon><Reading /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.courseCount?.toLocaleString() || 0 }}</div>
            <div class="stat-label">课程总数</div>
            <div class="stat-extra">今日新增: {{ todayOverview.newCourses || 0 }}</div>
          </div>
        </div>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card warning">
          <div class="stat-icon">
            <el-icon><EditPen /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.examCount?.toLocaleString() || 0 }}</div>
            <div class="stat-label">考试总数</div>
            <div class="stat-extra">今日新增: {{ todayOverview.newExams || 0 }}</div>
          </div>
        </div>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card danger">
          <div class="stat-icon">
            <el-icon><ChatDotRound /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.newsCount?.toLocaleString() || 0 }}</div>
            <div class="stat-label">资讯总数</div>
            <div class="stat-extra">文章: {{ stats.articleCount || 0 }}</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 第二行统计卡片 -->
    <el-row :gutter="20" class="stats-row" v-loading="loading">
      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card info">
          <div class="stat-icon">
            <el-icon><Checked /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.taskCount?.toLocaleString() || 0 }}</div>
            <div class="stat-label">任务总数</div>
            <div class="stat-extra">今日新增: {{ todayOverview.newTasks || 0 }}</div>
          </div>
        </div>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card purple">
          <div class="stat-icon">
            <el-icon><Monitor /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.onlineUsers?.toLocaleString() || 0 }}</div>
            <div class="stat-label">在线用户</div>
            <div class="stat-extra">今日访问: {{ stats.todayVisits?.toLocaleString() || 0 }}</div>
          </div>
        </div>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card teal">
          <div class="stat-icon">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ getPageViews() }}</div>
            <div class="stat-label">页面浏览量</div>
            <div class="stat-extra">增长率: {{ getGrowthRate() }}%</div>
          </div>
        </div>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card orange">
          <div class="stat-icon">
            <el-icon><DataAnalysis /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.systemRunDays || 0 }}</div>
            <div class="stat-label">运行天数</div>
            <div class="stat-extra">活跃用户: {{ getActiveUsers() }}</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 今日概览 -->
    <el-card class="today-overview" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>今日数据概览</span>
          <el-tag type="success">{{ new Date().toLocaleDateString() }}</el-tag>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :xs="12" :sm="8" :lg="4">
          <div class="overview-item">
            <div class="overview-number">{{ getNewUsers() }}</div>
            <div class="overview-label">新增用户</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="8" :lg="4">
          <div class="overview-item">
            <div class="overview-number">{{ getVisits() }}</div>
            <div class="overview-label">访问量</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="8" :lg="4">
          <div class="overview-item">
            <div class="overview-number">{{ getPageViews() }}</div>
            <div class="overview-label">页面浏览</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="8" :lg="4">
          <div class="overview-item">
            <div class="overview-number">{{ getLoginCount() }}</div>
            <div class="overview-label">登录次数</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="8" :lg="4">
          <div class="overview-item">
            <div class="overview-number">{{ getActiveUsers() }}</div>
            <div class="overview-label">活跃用户</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="8" :lg="4">
          <div class="overview-item">
            <div class="overview-number">{{ getGrowthRate() }}%</div>
            <div class="overview-label">增长率</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <span>用户增长趋势</span>
          </template>
          <div class="chart-container">
            <div class="chart-placeholder" v-if="!userGrowthData.length">
              <el-icon><TrendCharts /></el-icon>
              <p>暂无数据</p>
            </div>
            <div v-else class="chart-data">
              <div v-for="item in userGrowthData.slice(0, 5)" :key="item.date" class="data-item">
                <span class="date">{{ item.date }}</span>
                <span class="value">新增: {{ item.newUsers }}</span>
                <span class="value">活跃: {{ item.activeUsers }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <span>系统访问统计</span>
          </template>
          <div class="chart-container">
            <div class="chart-placeholder" v-if="!accessStatsData?.totalVisits">
              <el-icon><DataAnalysis /></el-icon>
              <p>暂无数据</p>
            </div>
            <div v-else class="access-stats">
              <div class="stats-grid">
                <div class="stats-item">
                  <div class="stats-number">{{ accessStatsData?.totalVisits?.toLocaleString() || 0 }}</div>
                  <div class="stats-label">总访问量</div>
                </div>
                <div class="stats-item">
                  <div class="stats-number">{{ accessStatsData?.totalPageViews?.toLocaleString() || 0 }}</div>
                  <div class="stats-label">页面浏览量</div>
                </div>
                <div class="stats-item">
                  <div class="stats-number">{{ accessStatsData?.avgSessionDuration || '00:00:00' }}</div>
                  <div class="stats-label">平均会话时长</div>
                </div>
                <div class="stats-item">
                  <div class="stats-number">{{ ((accessStatsData?.bounceRate || 0) * 100).toFixed(1) }}%</div>
                  <div class="stats-label">跳出率</div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快捷操作 -->
    <el-card class="quick-actions">
      <template #header>
        <span>快捷操作</span>
      </template>
      <el-row :gutter="20">
        <el-col :xs="12" :sm="8" :lg="4">
          <el-button
            type="primary"
            icon="User"
            class="toolbar-button is-primary"
            @click="$router.push('/system/user')"
          >用户管理</el-button>
        </el-col>
        <el-col :xs="12" :sm="8" :lg="4">
          <el-button
            type="success"
            icon="Reading"
            class="toolbar-button is-success"
            @click="$router.push('/classroom/course')"
          >课程管理</el-button>
        </el-col>
        <el-col :xs="12" :sm="8" :lg="4">
          <el-button
            type="warning"
            icon="EditPen"
            class="toolbar-button is-warning"
            @click="$router.push('/exam/exam')"
          >考试管理</el-button>
        </el-col>
        <el-col :xs="12" :sm="8" :lg="4">
          <el-button
            type="info"
            icon="Monitor"
            class="toolbar-button is-info"
            @click="$router.push('/coding/problem')"
          >编程题目</el-button>
        </el-col>
        <el-col :xs="12" :sm="8" :lg="4">
          <el-button
            type="danger"
            icon="Checked"
            class="toolbar-button is-danger"
            @click="$router.push('/task/task')"
          >任务管理</el-button>
        </el-col>
        <el-col :xs="12" :sm="8" :lg="4">
          <el-button
            type="primary"
            icon="ChatDotRound"
            class="toolbar-button is-primary"
            @click="$router.push('/news/news')"
          >资讯管理</el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Reading, EditPen, ChatDotRound, TrendCharts, DataAnalysis, Monitor, Checked } from '@element-plus/icons-vue'
import { getDashboardStats, getUserGrowthTrend, getSystemAccessStats, getTodayOverview } from '@/api/dashboard'

// 响应式数据
const loading = ref(true)
const stats = ref({
  userCount: 0,
  courseCount: 0,
  examCount: 0,
  newsCount: 0,
  articleCount: 0,
  taskCount: 0,
  productCount: 0,
  chatRoomCount: 0,
  todayNewUsers: 0,
  todayVisits: 0,
  onlineUsers: 0,
  systemRunDays: 0
})

const todayOverview = ref({
  newUsers: 0,
  visits: 0,
  pageViews: 0,
  newArticles: 0,
  newCourses: 0,
  newExams: 0,
  newTasks: 0,
  activeUsers: 0,
  loginCount: 0,
  registerCount: 0,
  growthRate: 0
})

const userGrowthData = ref([])
const accessStatsData = ref({})

// 安全的数据访问函数
const getPageViews = () => {
  try {
    const value = todayOverview.value?.pageViews
    return value ? value.toLocaleString() : '0'
  } catch (error) {
    console.error('获取页面浏览量失败:', error)
    return '0'
  }
}

const getGrowthRate = () => {
  try {
    const rate = todayOverview.value?.growthRate || 0
    return (rate * 100).toFixed(1)
  } catch (error) {
    console.error('获取增长率失败:', error)
    return '0.0'
  }
}

const getActiveUsers = () => {
  try {
    return todayOverview.value?.activeUsers || 0
  } catch (error) {
    console.error('获取活跃用户失败:', error)
    return 0
  }
}

const getNewUsers = () => {
  try {
    return todayOverview.value?.newUsers || 0
  } catch (error) {
    console.error('获取新增用户失败:', error)
    return 0
  }
}

const getVisits = () => {
  try {
    const value = todayOverview.value?.visits
    return value ? value.toLocaleString() : '0'
  } catch (error) {
    console.error('获取访问量失败:', error)
    return '0'
  }
}

const getLoginCount = () => {
  try {
    return todayOverview.value?.loginCount || 0
  } catch (error) {
    console.error('获取登录次数失败:', error)
    return 0
  }
}

// 获取仪表盘统计数据
const getStats = async () => {
  try {
    const response = await getDashboardStats()
    if (response.code === 200) {
      stats.value = response.data
    } else {
      ElMessage.error(response.message || '获取统计数据失败')
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')

    // 使用模拟数据作为后备
    stats.value = {
      userCount: 1234,
      courseCount: 89,
      examCount: 156,
      newsCount: 234,
      articleCount: 178,
      taskCount: 92,
      productCount: 45,
      chatRoomCount: 12,
      todayNewUsers: 25,
      todayVisits: 1250,
      onlineUsers: 68,
      systemRunDays: 365
    }
  }
}

// 获取今日概览数据
const getTodayData = async () => {
  try {
    const response = await getTodayOverview()
    if (response.code === 200 && response.data) {
      todayOverview.value = { ...todayOverview.value, ...response.data }
    } else {
      // 使用模拟数据
      todayOverview.value = {
        newUsers: 25,
        visits: 1250,
        pageViews: 3680,
        newArticles: 5,
        newCourses: 2,
        newExams: 3,
        newTasks: 8,
        activeUsers: 156,
        loginCount: 289,
        registerCount: 25,
        growthRate: 0.15
      }
    }
  } catch (error) {
    console.error('获取今日概览失败:', error)
    // 使用模拟数据
    todayOverview.value = {
      newUsers: 25,
      visits: 1250,
      pageViews: 3680,
      newArticles: 5,
      newCourses: 2,
      newExams: 3,
      newTasks: 8,
      activeUsers: 156,
      loginCount: 289,
      registerCount: 25,
      growthRate: 0.15
    }
  }
}

// 获取用户增长趋势
const getUserGrowth = async () => {
  try {
    const response = await getUserGrowthTrend()
    if (response.code === 200) {
      userGrowthData.value = response.data
    }
  } catch (error) {
    console.error('获取用户增长趋势失败:', error)
  }
}

// 获取访问统计
const getAccessStats = async () => {
  try {
    const response = await getSystemAccessStats()
    if (response.code === 200) {
      accessStatsData.value = response.data
    }
  } catch (error) {
    console.error('获取访问统计失败:', error)
  }
}

// 初始化数据
const initData = async () => {
  loading.value = true
  try {
    // 确保数据对象已初始化
    if (!todayOverview.value) {
      todayOverview.value = {
        newUsers: 0,
        visits: 0,
        pageViews: 0,
        newArticles: 0,
        newCourses: 0,
        newExams: 0,
        newTasks: 0,
        activeUsers: 0,
        loginCount: 0,
        registerCount: 0,
        growthRate: 0
      }
    }

    await Promise.all([
      getStats(),
      getTodayData(),
      getUserGrowth(),
      getAccessStats()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  console.log('Dashboard组件挂载，开始初始化数据')
  console.log('todayOverview初始值:', todayOverview.value)
  initData()
})
</script>

<style lang="scss" scoped>
@use 'sass:color';
@use '@/styles/variables.scss' as *;

.dashboard-container {
  padding: $spacing-base;
  background: $bg-color;
  min-height: calc(100vh - #{$header-height});
}

.dashboard-text {
  text-align: center;
  margin-bottom: $spacing-large;
  
  h1 {
    color: $text-color-primary;
    margin-bottom: $spacing-small;
  }
  
  p {
    color: $text-color-secondary;
  }
}

.stats-row {
  margin-bottom: $spacing-large;
}

.stat-card {
  background: #fff;
  border-radius: $border-radius-large;
  padding: $spacing-large;
  box-shadow: $box-shadow-base;
  display: flex;
  align-items: center;
  margin-bottom: $spacing-base;
  transition: $transition-base;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: $box-shadow-light;
  }
  
  .stat-icon {
    font-size: 48px;
    margin-right: $spacing-base;
    
    .el-icon {
      color: #fff;
    }
  }
  
  .stat-content {
    flex: 1;
    
    .stat-number {
      font-size: 32px;
      font-weight: bold;
      color: #fff;
      margin-bottom: 4px;
    }
    
    .stat-label {
      font-size: $font-size-base;
      color: rgba(255, 255, 255, 0.8);
    }

    .stat-extra {
      font-size: $font-size-small;
      color: rgba(255, 255, 255, 0.7);
      margin-top: 4px;
    }
  }

  &.primary {
    background: linear-gradient(135deg, $primary-color 0%, color.adjust($primary-color, $lightness: 10%) 100%);
  }

  &.success {
    background: linear-gradient(135deg, $success-color 0%, color.adjust($success-color, $lightness: 10%) 100%);
  }

  &.warning {
    background: linear-gradient(135deg, $warning-color 0%, color.adjust($warning-color, $lightness: 10%) 100%);
  }

  &.danger {
    background: linear-gradient(135deg, $danger-color 0%, color.adjust($danger-color, $lightness: 10%) 100%);
  }

  &.info {
    background: linear-gradient(135deg, #17a2b8 0%, color.adjust(#17a2b8, $lightness: 10%) 100%);
  }

  &.purple {
    background: linear-gradient(135deg, #6f42c1 0%, color.adjust(#6f42c1, $lightness: 10%) 100%);
  }

  &.teal {
    background: linear-gradient(135deg, #20c997 0%, color.adjust(#20c997, $lightness: 10%) 100%);
  }

  &.orange {
    background: linear-gradient(135deg, #fd7e14 0%, color.adjust(#fd7e14, $lightness: 10%) 100%);
  }
}

.today-overview {
  margin-bottom: $spacing-large;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .overview-item {
    text-align: center;
    padding: $spacing-base;

    .overview-number {
      font-size: 24px;
      font-weight: bold;
      color: $primary-color;
      margin-bottom: 4px;
    }

    .overview-label {
      font-size: $font-size-small;
      color: $text-color-secondary;
    }
  }
}

.charts-row {
  margin-bottom: $spacing-large;
}

.chart-card {
  margin-bottom: $spacing-base;

  .chart-container {
    height: 300px;

    .chart-placeholder {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: $text-color-secondary;

      .el-icon {
        font-size: 64px;
        margin-bottom: $spacing-base;
      }
    }

    .chart-data {
      padding: $spacing-base;

      .data-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: $spacing-small 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .date {
          font-weight: 500;
          color: $text-color-primary;
        }

        .value {
          font-size: $font-size-small;
          color: $text-color-secondary;
          margin-left: $spacing-small;
        }
      }
    }

    .access-stats {
      padding: $spacing-base;
      height: 100%;
      display: flex;
      align-items: center;

      .stats-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: $spacing-base;
        width: 100%;

        .stats-item {
          text-align: center;
          padding: $spacing-base;
          background: $bg-color-light;
          border-radius: $border-radius-base;

          .stats-number {
            font-size: 20px;
            font-weight: bold;
            color: $primary-color;
            margin-bottom: 4px;
          }

          .stats-label {
            font-size: $font-size-small;
            color: $text-color-secondary;
          }
        }
      }
    }
  }
}

.quick-actions {
  .el-row {
    margin-top: 10px;
    margin-bottom: 10px;
  }
  
  .el-col {
    display: flex;
    justify-content: center;
    margin-bottom: 10px;
  }
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: $spacing-small;
  }
  
  .stat-card {
    padding: $spacing-base;
    
    .stat-icon {
      font-size: 32px;
    }
    
    .stat-number {
      font-size: 24px;
    }
  }
}
</style>
